//
//  DDDPlusBaseWKWebVC.swift
//  DingDongZP
//
//  Created by LeMac on 17/1/12.
//  Copyright © 2017年 51ledian.com. All rights reserved.
//

import UIKit
import WebKit

class DDDPlusBaseWKWebVC: UIViewController {
    
    
    var url:String?
    var backItem:UIBarButtonItem?
    var closeItem:UIBarButtonItem?
    var leftItems:NSMutableArray?
    var webView:WKWebView?
    var progressView:UIProgressView?
    
    override func viewDidLoad() {
        
        setupView()
        initData()
        
    }
    
    func initData() {
        
        guard let url = NSURL.init(string: url ?? "") else { return }
        webView!.loadRequest(NSURLRequest.init(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 5))
        
        self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:LDFont.Font14,NSForegroundColorAttributeName:LDGolbalColor.White]
        
        
        RACObserve(self, "webView.estimatedProgress").subscribeNext { [weak self](obj) in
            
            guard let progress = obj as? Float else { return }
            debugPrint(progress)
            self?.progressView?.progress = progress
        }
        
    }
    
//    override func viewWillAppear(animated: Bool) {
//        
//        progressView?.removeFromSuperview()
//    }
    
    deinit {
        progressView?.removeFromSuperview()
    }
    
    func setupView() {
        
        
        
        //webview
        let configure = WKWebViewConfiguration()
        configure.allowsInlineMediaPlayback = true
        configure.userContentController = WKUserContentController()
        configure.userContentController.addScriptMessageHandler(self, name: "DPLUS")
        
        webView = WKWebView.init(frame: CGRectZero , configuration: configure)
        webView?.allowsBackForwardNavigationGestures = true
        webView?.navigationDelegate = self
        webView?.UIDelegate = self
        view.addSubview(webView!)
        
        webView?.snp_makeConstraints(closure: { (make) in
            make.top.left.equalTo(0)
            make.bottom.right.equalTo(0)
        })
        
        
        
        //progressview
        progressView = UIProgressView.init(progressViewStyle: UIProgressViewStyle.Bar)
        progressView!.frame = CGRectMake(0, LDFrame.NavH - 1, LDFrame.ScreenWidth, 1);
        progressView?.tintColor = UIColor.blueColor()
        navigationController?.view.addSubview(progressView!)
        
        
    
        //backlogo
        backItem = UIBarButtonItem().bk_initWithImage(UIImage(named: "返回"), style: .Done) { [weak self](obj) in
            
            
            if self?.webView?.canGoBack == true {
                self?.webView?.goBack()
            } else {
                self?.navigationController?.popViewControllerAnimated(true)
            }
            
        } as?UIBarButtonItem

        //closeitem
//        closeItem = UIBarButtonItem().bk_initWithImage(UIImage(named: "close_item"), style: .Done) { [weak self](obj) in
//            
//            self?.navigationController?.popViewControllerAnimated(true)
//        } as?UIBarButtonItem
        
        closeItem = UIBarButtonItem().bk_initWithTitle("关闭 ", style: UIBarButtonItemStyle.Done, handler: {[weak self] (obj) in
            
            self?.navigationController?.popViewControllerAnimated(true)
        })as? UIBarButtonItem
        closeItem?.setBackButtonTitlePositionAdjustment(UIOffset.init(horizontal: -10, vertical: 0), forBarMetrics: UIBarMetrics.Compact)
       
        
        
    }
    
}

extension DDDPlusBaseWKWebVC:WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate {
   
    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        //window.webkit.messageHandlers.DPLUS.postMessage({body:message});
        if message.name == "DPLUS" {
            //根据传递的 dict判断
            let dict = message.body as? NSDictionary
        }
    }
    
    
    //开始
    func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        progressView?.hidden = false;
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }
    
    func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
        
    }
    
    //完成
    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        
        progressView?.hidden = true
        title = webView.title
        
        if webView.canGoBack {
            
            navigationItem.leftBarButtonItems = [backItem!,closeItem!]
            navigationController?.interactivePopGestureRecognizer!.enabled = false;
        } else {
            navigationItem.leftBarButtonItems = [backItem!]
            navigationController?.interactivePopGestureRecognizer!.enabled = true;
        }
    }
    //加载失败
    func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
        
        LDShowHUB.shareInstance.showToastNoti("连接错误错误")
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }
}
